﻿Imports System.Windows.Threading

Public Class Alerter

    Private Shared BalloonTimer As DispatcherTimer
    Private Shared BalloonPlograms As New Queue(Of LiveProgram)
    Private Shared NotifyIcon As Forms.NotifyIcon
    Private Shared Settings As UserSettings

    Private Sub New()
    End Sub

    Private Shared _alertedProgramIds As New List(Of String)
    Public Shared ReadOnly Property AlertedProgramIds() As IList(Of String)
        Get
            Return DirectCast(_alertedProgramIds, IList(Of String))
        End Get
    End Property

    Public Shared Sub SetNotifyIcon(ByVal notifyIcon As Forms.NotifyIcon)
        Alerter.NotifyIcon = notifyIcon
        AddHandler Alerter.NotifyIcon.BalloonTipClicked, AddressOf NotifyIcon_BalloonTipClicked
    End Sub

    Public Shared Sub SetUserSetting(ByVal settings As UserSettings)
        Alerter.Settings = settings
    End Sub

    Public Shared Sub Alert(ByVal targets As IList(Of LiveProgram))

        ' Alert Window
        If settings.AlertWindowEnabled Then
            For Each p In targets
                Dim window = New AlertWindow(p)
                window.Show()
            Next
        End If

        ' Mail
        If Settings.EmailEnabled Then
            For Each p In targets
                Dim title = p.StartDateTime.ToString("HH:mm") & " " & p.Community.Name
                Dim body = p.Title & vbCrLf & p.Content & vbCrLf & "ニコ生アラート（仮）"
                SendMail(title, body)
            Next
        End If

        ' Balloon
        If settings.BalloonEnabled Then

            If BalloonTimer Is Nothing Then
                BalloonTimer = New DispatcherTimer
                AddHandler BalloonTimer.Tick, AddressOf ShowBalloon
            End If
            If BalloonPlograms.Count = 0 Then
                BalloonTimer.Interval = New TimeSpan(1)
            End If

            For Each p In targets
                BalloonPlograms.Enqueue(p)
            Next
            BalloonTimer.Start()
        End If

        ' Web
        If settings.WebOpeningEnabled Then
            For Each p In targets
                OpenUri(p.Uri)
            Next
        End If

        ' Sound
        If settings.SoundEnabled Then
            PlaySound(settings.SoundFile)
        End If
    End Sub

    Private Shared Sub ShowBalloon(ByVal sender As Object, ByVal e As EventArgs)
        BalloonTimer.Stop()

        Dim program = BalloonPlograms.Dequeue

        If NotifyIcon IsNot Nothing Then
            NotifyIcon.BalloonTipTitle = program.Community.Name
            NotifyIcon.BalloonTipText = program.Title & vbCrLf & _
                                        program.Content & vbCrLf & _
                                        program.StartDateTime.ToString("HH:mm") & _
                                        "(残り" & program.StartDateTime.AddMinutes(30).Subtract(Now).Minutes.ToString & "分)" ' TODO Magic Num 30

            NotifyIcon.Tag = program.Uri
            NotifyIcon.ShowBalloonTip(5000)
        End If

        If BalloonPlograms.Count > 0 Then
            BalloonTimer.Interval = New TimeSpan(0, 0, 5)
            BalloonTimer.Start()
        End If
    End Sub

    Private Shared Sub NotifyIcon_BalloonTipClicked(ByVal sender As Object, ByVal e As System.EventArgs)
        Alerter.OpenUri(DirectCast(NotifyIcon.Tag, Uri))
    End Sub

    Public Shared Sub OpenUri(ByVal uri As Uri)
        Try
            If Alerter.Settings.WebBrowserPath.Trim = "" Then
                Process.Start(uri.ToString)
            Else
                Process.Start(Alerter.Settings.WebBrowserPath, uri.ToString)
            End If
        Catch ex As Exception
            ' Ignore
        End Try
    End Sub


    Public Shared Sub TestPlaySound(ByVal file As String)
        PlaySound(file)
    End Sub

    Private Shared Sub PlaySound(ByVal file As String)
        Try
            If Not System.IO.File.Exists(file) Then
                Exit Sub
            End If

            Dim player = New System.Media.SoundPlayer
            player.SoundLocation = file
            player.Play()
            player.Dispose()
        Catch ex As Exception
            ' Ignore
        End Try
    End Sub

    Private Shared Sub SendMail(ByVal title As String, ByVal body As String)
        Dim email = Alerter.Settings.Email
        Dim msg As New System.Net.Mail.MailMessage()
        Dim enc = System.Text.Encoding.GetEncoding("Shift_JIS")

        Try
            msg.SubjectEncoding = enc
            msg.BodyEncoding = enc
            msg.From = New System.Net.Mail.MailAddress(email, "ニコ生アラート（仮）", enc)
            msg.To.Add(New System.Net.Mail.MailAddress(email, email, enc))

            msg.Subject = title
            msg.Body = body

            Dim client = New System.Net.Mail.SmtpClient()
            client.Host = Alerter.Settings.SmtpServer
            client.Port = Alerter.Settings.Port

            client.Send(msg)
        Catch ex As Exception

        End Try

    End Sub

    Public Shared Sub SendTestMail(ByVal title As String, ByVal body As String, ByVal email As String, ByVal server As String, ByVal port As Integer)

        'Dim email = Alerter.Settings.Email
        Dim msg As New System.Net.Mail.MailMessage()
        Dim enc = System.Text.Encoding.GetEncoding("Shift_JIS")
        Try
            msg.SubjectEncoding = enc
            msg.BodyEncoding = enc
            msg.From = New System.Net.Mail.MailAddress(email, "ニコ生アラート（仮）", enc)
            msg.To.Add(New System.Net.Mail.MailAddress(email, email, enc))

            msg.Subject = title
            msg.Body = body

            Dim client = New System.Net.Mail.SmtpClient()
            client.Host = server
            client.Port = port

            client.Send(msg)

            'SendMail("テスト送信", "ニコ生アラート（仮）テスト")
        Catch ex As Exception

        End Try

    End Sub



End Class
